//
//  HiRootController.m
//  HiCar
//
//  Created by 丁一 on 2018/12/12.
//  Copyright © 2018 丁一. All rights reserved.
//

#import "HiRootController.h"
#import "HomeController.h"
#import "CenterController.h"
#import "XHTwitterPaggingViewer.h"
#import "XHTableViewController.h"
#import "CarInitViewModel.h"
#import "LearnController.h"
#import "SuiJiViewModel.h"
#import "LearnViewModel.h"
#import "JoneCunChu.h"
#import "MementoCenter.h"
#import "NSObject+MementoCenter.h"
#import "ChatHController.h"
#import "ChatSql.h"
#import "GetNewsCVModel.h"
#import "RootSuperAction.h"
#import "ABCJoensTabe.h"
#import "AFGetUsermdoel.h"

@interface HiRootController ()<UITabBarControllerDelegate,CarInitDelegate,SuijiSideNewsDelegate,GetLearnListDelegate,GetNewsCDelegate>{
    ChatSql        *sqliteletter;
    NSUInteger      letter_Count;
}

@property (nonatomic, strong) UINavigationController *NAV_SlideHome;
@property (nonatomic, strong) UINavigationController *NAV_Home;
@property (nonatomic, strong) UINavigationController *NAV_Center;
@property (nonatomic, strong) UINavigationController *NAV_Learn;
@property (nonatomic, strong) UINavigationController *NAV_Chat;

@property (nonatomic, strong) UITabBarItem           *SlideHome_tabbar;
@property (nonatomic, strong) UITabBarItem           *Home_tabbar;
@property (nonatomic, strong) UITabBarItem           *Center_tabbar;
@property (nonatomic, strong) UITabBarItem           *Learn_tabbar;
@property (nonatomic, strong) UITabBarItem           *Chat_tabbar;

@end

@implementation HiRootController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _NAV_SlideHome    = [[UINavigationController alloc] initWithRootViewController:self.SideHome_VC];

    _NAV_SlideHome.tabBarItem                 = _SlideHome_tabbar;
    
    _NAV_Home    = [[UINavigationController alloc] initWithRootViewController:self.Home_VC];
    _NAV_Home.tabBarItem                 = _Home_tabbar;
    
    _NAV_Center    = [[UINavigationController alloc] initWithRootViewController:self.Center_VC];
    _NAV_Center.tabBarItem                 = _Center_tabbar;
    
    _NAV_Learn    = [[UINavigationController alloc] initWithRootViewController:self.Learn_VC];
    _NAV_Learn.tabBarItem                 = _Learn_tabbar;
    
    _NAV_Chat    = [[UINavigationController alloc] initWithRootViewController:self.Caht_VC];
    _NAV_Chat.tabBarItem                 = _Chat_tabbar;
    
    NSArray *array_tabbarvc = @[_NAV_Learn,_NAV_Home,_NAV_Chat,_NAV_Center];
    [self setViewControllers:array_tabbarvc animated:YES];
    
    self.delegate             = self;
    
    [self car_init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(car_init)
                                                 name:ROOTGOTOLOGIN
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(show_weidu)
                                                 name:CHONGXINTIXINGCOUNT
                                               object:nil];
    
    [self loadnew];
    
    sqliteletter = [[ChatSql alloc] init];

    [[[AFGetUsermdoel alloc] init] setbanck_color];

    [self changeuser_cgd_shf:@"UYSHDDD"];
}

- (void)get_news_chat{
    NSMutableDictionary *senddic = [NSMutableDictionary new];
    [senddic setValue:[UserModel info].userid forKey:@"userid"];
    
    GetNewsCVModel *viewmodel = [[GetNewsCVModel alloc] init:senddic];
    viewmodel.delegate = self;
}

-(void)Succes:(int)value array:(NSMutableArray *)array{
    if (value==1) {
        
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ChatModel *Model = (ChatModel *)obj;
            [self->sqliteletter Insertdata:Model];
        }];
        
        [self show_weidu];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NEW_CHATLIST_Key object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:NEW_Center_Key object:nil];
    }
}

- (void)show_weidu{
    letter_Count = [sqliteletter selectdatanews].count;
    
    NSInteger zong_count = letter_Count;
    
    if (zong_count==0) {
        _Chat_tabbar.badgeValue=nil;
    }else{
        _Chat_tabbar.badgeValue=[NSString stringWithFormat:@"%li",(long)zong_count];
    }

    [UIApplication sharedApplication].applicationIconBadgeNumber = zong_count;
}

-(void)changeuser_cgd_shf:(NSString *)cun_keysdf{
    
    __block BOOL is_ok_sdff = NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        if ([DEFAULTS objectForKey:ROOTSITUZHANSHI]) {
            NSLog(@"%@",[DEFAULTS objectForKey:ROOTSITUZHANSHI]);
            is_ok_sdff = YES;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (is_ok_sdff) {
                ABCJoensTabe *actskf = [[ABCJoensTabe alloc] init];
                
                AppDelegate * adsfhjde = (AppDelegate*)[UIApplication sharedApplication].delegate;
                adsfhjde.window.rootViewController = [actskf getnvc];
            }
            
        });
    });
}

- (void)loadnew{
    SuiJiViewModel *viewmodel = [[SuiJiViewModel alloc] init:@{@"type":@"1"}];
    viewmodel.delegate =self;
    
    LearnViewModel *lviewmodel = [[LearnViewModel alloc] init:@{@"type":@"1"}];
    lviewmodel.delegate =self;
}

- (void)SuijiSideNewsSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    if (value==1) {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        shuju.JoneArray=array;
        [shuju saveStateWithKey:@"BannerList"];
    }
}

- (void)GetLearnListSucces:(int)value array:(NSMutableArray *)array{
    if (value==1) {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        shuju.JoneArray=array;
        [shuju saveStateWithKey:@"LearnList"];
    }
}

-(void)car_init{
    if ([UserModel info].userid) {
        NSMutableDictionary *senddic = [NSMutableDictionary new];
        [senddic setValue:[UserModel info].userid forKey:@"userid"];
        CarInitViewModel *viewmodel = [[CarInitViewModel alloc] init:senddic];
        viewmodel.delegate=self;
        
         [self get_news_chat];
    }else{
        [DEFAULTS removeObjectForKey:Comment_Count_key];
    }
}

- (void)CarInitSucces:(int)value dic:(NSDictionary *)dic{
    if (value==1) {
        
        [DEFAULTS setValue:[dic objectForKey:@"Comment_Count"] forKey:Comment_Count_key];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NEW_Side_Key object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:NEW_Center_Key object:nil];
    }
}

/*
 *SlideHome页面
 */
- (XHTwitterPaggingViewer *)SideHome_VC{
    if (_SideHome_VC == nil) {
        _SideHome_VC                         = [[XHTwitterPaggingViewer alloc] init];
        
        XHTableViewController *tableViewController0 = [XHTableViewController new];
        tableViewController0.RootTabbar = self;
        tableViewController0.title=@"推荐";
        tableViewController0.type=100;
        XHTableViewController *tableViewController1 = [XHTableViewController new];
        tableViewController1.RootTabbar = self;
        tableViewController1.title=@"A股";
        tableViewController1.type=0;
        XHTableViewController *tableViewController2 = [XHTableViewController new];
        tableViewController2.RootTabbar = self;
        tableViewController2.title=@"港股";
        tableViewController2.type=1;
        XHTableViewController *tableViewController3 = [XHTableViewController new];
        tableViewController3.RootTabbar = self;
        tableViewController3.title=@"美股";
        tableViewController3.type=2;
//        XHTableViewController *tableViewController5 = [XHTableViewController new];
//        tableViewController5.RootTabbar = self;
//        tableViewController5.title=@"外汇";
//        tableViewController5.type=4;
//        XHTableViewController *tableViewController6 = [XHTableViewController new];
//        tableViewController6.RootTabbar = self;
//        tableViewController6.title=@"黄金";
//        tableViewController6.type=5;
        XHTableViewController *tableViewController4 = [XHTableViewController new];
        tableViewController4.RootTabbar = self;
        tableViewController4.title=@"其他";
        tableViewController4.type=3;
        _SideHome_VC.viewControllers = @[tableViewController0,tableViewController1, tableViewController2,tableViewController3,tableViewController4];
        
        _SlideHome_tabbar                     = [[UITabBarItem alloc] initWithTitle:@"热点" image:[UIImage imageNamed:@"news"] selectedImage:[UIImage imageNamed:@"news"]];
        _SlideHome_tabbar.tag                 = 1;
    }
    return _SideHome_VC;
}

/*
 *Home页面
 */
- (HomeController *)Home_VC{
    if (_Home_VC == nil) {
        _Home_VC                         = [[HomeController alloc] init];
        _Home_VC.navigationItem.title    = @"交流";
        _Home_tabbar                     = [[UITabBarItem alloc] initWithTitle:@"交流" image:[UIImage imageNamed:@"jiaoliu"] selectedImage:[UIImage imageNamed:@"jiaoliu"]];
        _Home_tabbar.tag                 = 1;
    }
    return _Home_VC;
}

/*
 *Home页面
 */
- (ChatHController *)Caht_VC{
    if (_Caht_VC == nil) {
        _Caht_VC                         = [[ChatHController alloc] init];
        _Caht_VC.navigationItem.title    = @"私信";
        _Chat_tabbar                     = [[UITabBarItem alloc] initWithTitle:@"私信" image:[UIImage imageNamed:@"chat"] selectedImage:[UIImage imageNamed:@"chat"]];
        _Chat_tabbar.tag                 = 1;
    }
    return _Caht_VC;
}

/*
 *Learn页面
 */
- (LearnController *)Learn_VC{
    if (_Learn_VC == nil) {
        _Learn_VC                         = [[LearnController alloc] init];
        _Learn_VC.navigationItem.title    = @"首页";
        _Learn_tabbar                     = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"xuexi"] selectedImage:[UIImage imageNamed:@"xuexi"]];
        _Learn_tabbar.tag                 = 1;
    }
    return _Learn_VC;
}

/*
 *canter页面
 */
- (CenterController *)Center_VC{
    if (_Center_VC == nil) {
        _Center_VC                         = [[CenterController alloc] init];
        _Center_VC.navigationItem.title    = @"我的";
        _Center_tabbar                     = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"center"] selectedImage:[UIImage imageNamed:@"center"]];
        _Center_tabbar.tag                 = 3;
    }
    return _Center_VC;
}

#pragma mark - UITabbar代理
//- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
//    if (([_NAV_Nearby.topViewController isKindOfClass:[HiNearbyController class]] ||[_NAV_Home.topViewController isKindOfClass:[XHTwitterPaggingViewer class]] || [_NAV_Chat.topViewController isKindOfClass:[HiChatController class]] || [_NAV_Center.topViewController isKindOfClass:[HiCenterController class]]) ){
//        if ([UserModel info].userid) {
//            if (![UserModel info].name||[[UserModel info].name isEqualToString:@""]) {
//                [self gotofulluser];
//                return NO;
//            }
//            return YES;
//        }else{
//            [self gotologin];
//            return NO;
//        }
//    }else{
//        return YES;
//    }
//}

-(void)GPS_open{
    //判断定位是否开启
    if ([CLLocationManager locationServicesEnabled]){
        //ok
    }else{
        //@"你已关闭定位";
    }
    
    self.manager.delegate = self;
    // 判断操作系统的版本
    if( [[UIDevice currentDevice].systemVersion doubleValue] >= 8.0){
        [self.manager requestWhenInUseAuthorization];
        
    }else{
        [self.manager startUpdatingLocation];
    }
}

////// ------    定位   -----  ／／／／／／／
- (CLLocationManager *)manager{
    if (_manager == nil) {
        _manager = [[CLLocationManager alloc] init];
    }
    return _manager;
}

- (CLGeocoder *) geoCoder{
    if (_geoCoder == nil) {
        _geoCoder = [[CLGeocoder alloc]init];
    }
    return _geoCoder;
}

#pragma mark-CLLocationManagerDelegate用户是否同意
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    switch (status) {
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            //和对应
            //设置精度
            self.manager.distanceFilter = 20;
            [self.manager startUpdatingLocation];
            break;
        case kCLAuthorizationStatusDenied:
            
            break;
        default:
            break;
    }
}

#pragma mark 用户的位置法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    [[NSUserDefaults
      standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",nil] forKey:@"AppleLanguages"];
    
    for (CLLocation *location in locations) {
        
        [self.geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (error == nil) {
                CLLocation *loc = [locations lastObject];
                CLPlacemark *mark    = placemarks.lastObject;
                
                //                [DEFAULTS setValue:[NSString stringWithFormat:@"%f",loc.coordinate.latitude] forKey:City_WeiDu_Key];
                //                [DEFAULTS setValue:[NSString stringWithFormat:@"%f",loc.coordinate.longitude] forKey:City_JinDu_Key];
                //                NSLog(@"纬度=%f，经度=%f",loc.coordinate.latitude,loc.coordinate.longitude);
                
                [DEFAULTS setValue:[NSString stringWithFormat:@"%f",loc.coordinate.latitude] forKey:City_WeiDu_Key];
                [DEFAULTS setValue:[NSString stringWithFormat:@"%f",loc.coordinate.longitude] forKey:City_JinDu_Key];
                
                NSLog(@"%@",mark.locality);
            }
        }];
    }
    //手动停止定位
    [self.manager stopUpdatingLocation];
}

@end
